<?php


namespace App\Helpers;


use App\Helpers\WatchDog\DingTalk\DingTalkHelper;
use App\Helpers\WatchDog\LarkBot\LarkBotHelper;

class WatchDogHelper extends Helper
{
	// 发送警报的目标类型
	const WATCHDOG_TARGET_DINGDING = 'dingding';
	const WATCHDOG_TARGET_FEISHU   = 'feishu';
	// $accessTokens
	private static string $accessTokens = "";
	// 默认发送
	private static bool $defaultSend = true;

	/**
	 * 看门狗助手类
	 *
	 * @var LarkBotHelper|DingTalkHelper
	 */
	private static $watchDog = null;

	// 初始化token
	private static function initAccessToken()
	{
		if (static::$accessTokens) {
			return;
		}
		// 读取token 配置
		$accessTokens = env("WATCH_DOG_TOKENS", 'test');

		// 字符串转数组
		static::$accessTokens = $accessTokens;

		// 初始化token
		(static::$watchDog)::initAccessToken(static::$accessTokens);
	}

	private static function getWatchDog()
	{
		if (static::$watchDog == null) {
			// 读取发送目标配置
			$watchDogTarget = env("WATCH_DOG_TARGET", 'dingding');
			switch ($watchDogTarget) {
				case self::WATCHDOG_TARGET_FEISHU:
					// 飞书
					static::$watchDog = LarkBotHelper::class;
					break;
				default:
					// 钉钉
					static::$watchDog = DingTalkHelper::class;
			}

			// 初始化token
			static::initAccessToken();
		}

		// 设置默认发送状态(每一条记录都可能发送或者不发送)
		(static::$watchDog)::setDefaultSendStatus(static::$defaultSend);
	}

	// 设置默认发送状态：true-发送、false-不发送
	public static function setDefaultSendStatus(bool $status)
	{
		static::$defaultSend = $status;
	}

	/**
	 * 【关键词】「服务名称:服务的环境」异常关键词--Y-m-d,msg: 具体的内容json串
	 *
	 * @param string       $mark
	 * @param string|array $info
	 * @return string
	 */
	public static function makeMsg(string $mark, $info): string
	{
		if (!static::$defaultSend || !$info) {
			return "";
		}

		static::getWatchDog();

		return static::$watchDog::makeMsg($mark, $info);
	}

	/**
	 * text类型
	 *
	 * @param string $content
	 */
	public static function sendText(string $content)
	{
		if (!static::$defaultSend || !$content) {
			return;
		}

		static::getWatchDog();

		static::$watchDog::sendText($content);
	}

}

